<?php
class RoomTypesController extends AppController {
	public $name        = 'RoomTypes';
    public $helpers     = array('Html', 'Cache', 'Form', 'Javascript');
    public $cacheAction = array('index/' => '60'); // cache index View for 1 minute

    public function admin_add () {
        if (!empty($this->data)) {
            $this->TypeRoom->set($this->data);

            if (!$this->TypeRoom->validates()) {
                $json = $this->TypeRoom->invalidFields();
            } else if ($this->TypeRoom->save($this->data)) {
                $this->flash(__('Room type saved.', true), array('action'=>'index'));
            }
        }
    } // admin_add

    public function admin_axAdd () {
        Configure::write('debug', 0);
        $this->TypeRoom->set($this->data);
        $model = 'TypeRoom';
        $stt   = -1;

        if ($this->TypeRoom->validates()) {
            if ($this->TypeRoom->save($this->data)) {
                $stt             = 1;
                $json['message'] = __('New room type saved.', true);
            }
        } else {
            $err = $this->AdCategory->invalidFields();
            foreach ($err as $k=>$v) {
               $json['error'][] = array('id'=>$model.ucwords($k), 'field'=>$k, 'code'=>$v);
            }
        }

        header('X-JSON: { status:'.$stt.' }');
        $this->set('json', $json);
        $this->render(false, 'json');
    } // admin_axAdd

    public function admin_edit ($id=null) {
        if (empty($this->data)) {
            if (!$id) {
                //$this->Session->setFlash('<h4>'.__('Missing required id',true).'</h4>', 'default', array('class'=>'boxError'));
                $this->flash('<h4>'.__('Missing required id',true).'</h4>', 'index', 5);
            } else {
                $this->data = $this->TypeRoom->findById($id);
            }
        } else {
            if ($this->TypeRoom->save($this->data)) {
                $this->Session->setFlash('<h4>'.__('The Room Type has been saved.',true).'</h4>', 'default', array('class'=>'boxSuccess'));
                $this->redirect('/admin/roomtypes');
            }
        }
    } // admin_edit

    public function admin_delete ($id) {
        if (!$id) {
            $this->set('pageTitle', __('Missing Post Id.',true));
            $this->flash('<h4>'.__('Missing Post Id.',true).'</h4>', '/admin/roomtypes', 5);
            return false;
        } else if ($this->TypeRooms->del($id)) {
            $this->Session->setFlash('<h4>'.__('Room type has been deleted',true).'</h4>', 'default', array('class'=>'boxSuccess'));
            $this->redirect('/admin/roomtypes');
        }
    } // admin_delete

    public function admin_view ($id=null) {
        if (!$id) {
            $this->Session->setFlash('<h4>'.__('Missing required id',true).'</h4>', 'default', array('class'=>'boxError'));
        }
        $this->set('data', $this->TypeRooms->findById($id));
    } // admin_view


    public function rest_list ($ext='xml') {
        $data = $this->RoomType->find('all');
        $this->rest_render($ext, $data);
    } // rest_list


    public function listbox () {
        $data = $this->RoomType->find('all', array(
            'recursive' => -1,
            'fields'    => array('id', 'code', 'description'),
            'order'     => 'id ASC'
        ));

        $prefix  = isset($this->params['form']['prefix']) ? $this->params['form']['prefix'].'-' : '';
        $loadAll = isset($this->params['form']['all']) ? $this->params['form']['all'] : false;

        $this->set('data', $data);
        $this->set('prefix', $prefix);
        $this->set('loadAll', $loadAll);
        $this->render('ax.listbox', 'blank');
    } // listbox

    public function checkRoom () {
        $form = $this->params['form'];
        $type = $form['type'];
        $date = $form['date'];
        $room = $this->RoomType->availability($type, $date);
        $nite = $this->_totalNights($date);

        if ($room) {
            $json = array(
                'status' => true,
                'rooms'  => $room,
                'nights' => $nite
            );
        } else {
            $json = array(
                'status' => false,
                'mesg'   => __('An overbooking will result for this WalkIn.', true)
            );
        }

        $this->response($json);
    } // checkRoom

    public function checkRooms () {
        $form = $this->params['form'];
        $type = $form['type'];
        $date = $form['date'];
        $nite = $this->_totalNights($date);

        $rooms = array(
            'list'  => $this->RoomType->availability($type, $date, 1),
            'night' => $nite
        );

        $this->set('data', $rooms);
        $this->layout = 'blank';
    } // checkRooms

    public function availableRooms ($type, $checkin, $checkout) {
        $data = $this->RoomType->availability($type, array($checkin, $checkout), 2);
        $json = array(
            'total'   => 1,
            'page'    => 1,
            'records' => count($data),
            'rows'    => $data
        );

        $this->response($json);
    } // availableRooms

    public function total_nights () {
        $json = array(
            'status' => true,
            'nights' => $this->_totalNights($this->params['form']['date'])
        );

        $this->response($json);
    } // total_nights


    private function _totalAvailability ($roomTypeId, $date) {
        $this->RoomType->id = $roomTypeId;
        $totalRooms         = $this->RoomType->field('room_count');

        $this->loadModel('Stay');
        $count = $this->Stay->find('count', array(
            'conditions' => array(
                'Stay.date'         => $date,
                'Stay.room_type_id' => $roomTypeId,
            )
        ));

        $available = $totalRooms - $count;

        return $available;
    } // _totalAvailability

    private function _totalNights ($date) {
        if (is_array($date) && count($date) == 2) {
            list($day1, $month1, $year1) = split('[/.-]', $date[0]);
            list($day2, $month2, $year2) = split('[/.-]', $date[1]);
        } else {
            $day1   = date('d');
            $month1 = date('m');
            $year1  = date('Y');
            list($day2, $month2, $year2) = split('[/.-]', $date);
        }

        $checkin  = strtotime($year1.'-'.$month1.'-'.$day1);
        $checkout = strtotime($year2.'-'.$month2.'-'.$day2);
        $nights   = ($checkout - $checkin) / 86400;

        return $nights;
    } // _totalNights
} // RoomTypesController
?>